﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Upreader.Common;

namespace Upreader.Engine
{
    /// <summary>
    /// Contains methods for finding the right path for storing operation data
    /// </summary>
    public class DownloadDataStore
    {
        #region Methods

        public void WriteToFile(string downloadPath, Upreader.Application.Model.File file, Stream stream)
        {
            if (downloadPath == null)
                throw new ArgumentNullException("downloadPath");
            if (file == null)
                throw new ArgumentNullException("file");
            if (stream == null)
                throw new ArgumentNullException("stream");

            string path = GetFilePath(downloadPath, file.FileName);

            EnsureDirectory(path);

            using (Stream fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                fileStream.Position = fileStream.Length;
                stream.CopyTo(fileStream);
            }
        }

        public void EnsureDownloadPath(string rootPath, Upreader.Application.Model.Download download)
        {
            if (download == null)
                throw new ArgumentNullException("download");
            if (rootPath == null)
				throw new ArgumentNullException("rootPath");

            if (download.DownloadPath == null)
            {
                string title = download.Title;
                string originalPath = Path.Combine(rootPath, FileUtility.EncodePath(title));

                string path = originalPath;
                int number = 0;
                bool isValid = false;

                while (!isValid)
                {
                    if (!Directory.Exists(path))
                    {
                        download.DownloadPath = path;
                        isValid = true;
                    }
                    else
                    {
                        path = string.Format("{0} ({1})", originalPath, ++number);
                    }
                }

                download.DownloadPath = path;
            }
        }

        #endregion Methods

        #region Helpers

        private void EnsureDirectory(string path)
        {
            string directoryPath = Path.GetDirectoryName(path);

            if (!Directory.Exists(directoryPath))
                Directory.CreateDirectory(directoryPath);
        }

        private string GetFilePath(string downloadPath, string fileName)
        {
            if (downloadPath == null)
                throw new ArgumentNullException("downloadPath");
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            return Path.Combine(downloadPath, fileName);
        }

        #endregion // Helpers
    }
}
